import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_vant_kit/main.dart';
import 'package:crypto/crypto.dart';
import 'package:image_picker/image_picker.dart';
import 'package:uuid/uuid.dart';
import 'package:toast/toast.dart';
import 'package:intl/intl.dart';

import 'DioUtil.dart';
import 'util/SPUtil.dart';

class Upplatecode extends StatefulWidget {
  Upplatecode({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _UpplatecodeState createState() => _UpplatecodeState();
}

class _UpplatecodeState extends State<Upplatecode> {
  static var policMap = {
    "expiration": "2090-01-01T12:00:00.000Z",
    "conditions": [
      ["content-length-range", 0, 104857600]
    ]
  };

  //验证文本域
  static String policyText = jsonEncode(policMap);

  //进行utf8编码
  static List<int> policyTextUtf8 = utf8.encode(policyText);

  //进行base64编码
  static String policyBase64 = base64.encode(policyTextUtf8);

  //再次进行utf8编码
  static List<int> policy = utf8.encode(policyBase64);
  static String accesskey = 'fML9lIq05ka6dEkV2VG91Fh0WuyWBB';

  //进行utf8 编码
  static List<int> key = utf8.encode(accesskey);

  //通过hmac,使用sha1进行加密
  static List<int> signaturePre = new Hmac(sha1, key).convert(policy).bytes;

  //最后一步，将上述所得进行base64 编码
  String signature = base64.encode(signaturePre);

  String _imageUrl1;
  String _imageUrl2;
  String _imageUrl3;
  String _imageUrl4;
  String areaCode;
  int userId = 1;

  final _uplateFormKey = GlobalKey<FormState>();

  final List<String> electrTypeKeys = [
    'w2',
    'w3',
    'w4',
    'm2',
    'm3',
    'cj',
    'gb2',
    'ddmtc'
  ];
  final List<String> electrTypeLabels = [
    '二轮电动车',
    '三轮电动车',
    '四轮电动车',
    '二轮摩托车',
    '三轮摩托车',
    '残疾人',
    '国标二轮电动车',
    '电动摩托车'
  ];

  final List<PickerItem> electrTypeItems = [
    PickerItem('二轮电动车'),
    PickerItem('三轮电动车'),
    PickerItem('四轮电动车'),
    PickerItem('二轮摩托车'),
    PickerItem('三轮摩托车'),
    PickerItem('残疾人'),
    PickerItem('国标二轮电动车'),
    PickerItem('电动摩托车'),
  ];
  String electrType = "w2";
  String electrIns = "no";
  int electrTypeIndex = 0;
  int electrInsIndex = 0;

  TextEditingController _phoneCtrl = TextEditingController();
  TextEditingController _nameCtrl = TextEditingController();
  TextEditingController _cardIdCtrl = TextEditingController();
  TextEditingController _addressCtrl = TextEditingController();
  TextEditingController _plateCodeCtrl = TextEditingController();
  TextEditingController _frameCodeCtrl = TextEditingController();
  TextEditingController _engineCtrl = TextEditingController();
  TextEditingController _rfidCtrl = TextEditingController();
  TextEditingController _colorCtrl = TextEditingController();
  TextEditingController _brandCtrl = TextEditingController();

  void getImage(ImageSource source, int witchOne) async {
    File image = await ImagePicker.pickImage(source: source);
    if (image != null) {
      uploadImage(image, witchOne);
    }
  }

  void uploadImage(File _image, int witchOne) async {
    BaseOptions options = new BaseOptions();
    options.responseType = ResponseType.plain;
    Dio dio = new Dio(options);
    String fileName = new Uuid().v4();
    String filePath = _image.path;
    String imageType =
        filePath?.substring(filePath?.lastIndexOf("."), filePath?.length);
    FormData data = new FormData.fromMap({
      'Filename': fileName + imageType,
      'key': fileName + imageType,
      'policy': policyBase64,
      'OSSAccessKeyId': "LTAI4Fjo1zEfqFnuvrpYDZYZ",
      'success_action_status': '200', //让服务端返回200，不然，默认会返回204
      'Signature': signature,
      'file': MultipartFile.fromFileSync(filePath)
    });
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) {
          return Center(
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4.0),
                  color: Colors.white),
              padding: EdgeInsets.all(20),
              child: Loading(
                color: Colors.blueAccent,
                text: "正在上传图片...",
              ),
            ),
          );
        });

    try {
      Response response = await dio.post(
          "http://electr-imgserver.oss-cn-hangzhou.aliyuncs.com",
          data: data);
      if (response.statusCode == 200) {
        Toast.show("图片上传成功", context, duration: 2);
        switch (witchOne) {
          case 1:
            setState(() {
              _imageUrl1 = fileName + imageType;
            });
            break;
          case 2:
            setState(() {
              _imageUrl2 = fileName + imageType;
            });
            break;
          case 3:
            setState(() {
              _imageUrl3 = fileName + imageType;
            });
            break;
          case 4:
            setState(() {
              _imageUrl4 = fileName + imageType;
            });
            break;
        }
        Navigator.of(context).pop();
      } else {
        Toast.show("上传失败，请重试", context, duration: 3);
      }
    } on DioError catch (e) {
      Toast.show(e.message, context, duration: 3);
    }
  }

  bool _uploading = false;
  void saveElectrInfo() {
    String userId = SpUtil.preferences.getString("userId");
    String consumerSysCode = SpUtil.preferences.getString("consumerSysCode");
    if (isEmptyValue(_phoneCtrl.text) ||
        isEmptyValue(_cardIdCtrl.text) ||
        isEmptyValue(_rfidCtrl.text) ||
        isEmptyValue(_frameCodeCtrl.text) ||
        isEmptyValue(_plateCodeCtrl.text) ||
        isEmptyValue(areaCode) ||
        buyDate == null) {
      showDialog(
        context: context,
        builder: (_) {
          return NDialog(
            message: "请补充必填信息",
          );
        },
      );
      return;
    }
    setState(() {
      _uploading = true;
    });
    DioUtil.postHttp("electr/save", params: {
      "realName": _nameCtrl.text,
      "phone": _phoneCtrl.text,
      "idCard": _cardIdCtrl.text,
      "address": _addressCtrl.text,
      "areaCode": areaCode,
      "rfid": _rfidCtrl.text,
      "plateCode": _plateCodeCtrl.text,
      "frameCode": _frameCodeCtrl.text,
      "engine": _engineCtrl.text,
      "brandIndc": _brandCtrl.text,
      "color": _colorCtrl.text,
      "type": electrTypeKeys[electrTypeIndex],
      "userId": userId,
      "buyDate": formatDateWithYear(buyDate),
      "crteMngId": userId,
      "updtMngId": userId,
      "consumerSysCode": consumerSysCode,
      "imgUrl": _imageUrl1,
      "imgUrl2": _imageUrl2,
      "imgUrl3": _imageUrl3,
      "imgUrl4": _imageUrl4,
      "insDetailCode": insureKeys.length > 0 ? insureKeys[electrInsIndex] : 'no'
    }, onSuccess: (res) {
      setState(() {
        _uploading = false;
      });
      Map<String, dynamic> result = jsonDecode(res);
      if(result['code']!=0){
        Toast.show(result["msg"], context, duration: 3);
      }else{
        Toast.show("保存成功", context, duration: 3);
        resetForm();
      }
    });
  }

  DateTime buyDate;

  String formatDateWithYear(DateTime date) {
    return DateFormat('yyyy-MM-dd').format(date);
  }

  void resetForm() {
    _uplateFormKey.currentState.reset();
    _nameCtrl.text = "";
    _phoneCtrl.text = "";
    _cardIdCtrl.text = "";
    _addressCtrl.text = "";
    _rfidCtrl.text = "";
    _plateCodeCtrl.text = "";
    _frameCodeCtrl.text = "";
    _engineCtrl.text = "";
    _brandCtrl.text = "";
    _colorCtrl.text = "";
    setState(() {
      _imageUrl1 = "";
      _imageUrl2 = "";
      _imageUrl3 = "";
      _imageUrl4 = "";
      areaCode = "";
      areaNames = "";
      buyDate = null;
      electrInsIndex = 0;
      electrTypeIndex = 0;
      userId = 1;
    });
  }

  List<ActionSheetItem> actionList = [
    ActionSheetItem(name: "拍照"),
    ActionSheetItem(name: "相册")
  ];

  Future<int> _showActionSheet(BuildContext context, int witchOne) {
    return showCupertinoModalPopup(
        context: context,
        builder: (ctx) {
          var dialog = CupertinoActionSheet(
            title: Text("选择图片"),
            cancelButton: CupertinoActionSheetAction(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text("取消"),
            ),
            actions: <Widget>[
              CupertinoActionSheetAction(
                onPressed: () {
                  getImage(ImageSource.camera, witchOne);
                  Navigator.of(context).pop();
                },
                child: Text("拍照"),
              ),
              CupertinoActionSheetAction(
                onPressed: () {
                  getImage(ImageSource.gallery, witchOne);
                  Navigator.of(context).pop();
                },
                child: Text("从手机相册"),
              )
            ],
          );
          return dialog;
        });
  }

//  void _showActionSheetA(BuildContext c, int witchOne) {
//
//    ActionSheet(
//        actions: actionList,
//        cancelText: "取消",
//        onSelect: (action, index) {
//          print(index);
//          if(index == 0){
//            getImage(null,witchOne);
//          }else if(index == 1){
//            getImage(FileType.image, witchOne);
//          }
//        }).show(c);
//
//  }

  /// 初始化
  _UpplatecodeState() {
    getInsureList();
    loadAreas();
  }

  List<PickerItem> provincePickerItems = [];
  List<String> acodes = [];
  String areaNames = "";

  void loadAreas() {
    String userId = SpUtil.preferences.getString("userId");
    DioUtil.postHttp("sysMngArea/getAreaTreeByMngId/" + userId, params: {},
        onSuccess: (res) async {
      Map<String, dynamic> data = jsonDecode(res);
      if (data['data'] != null && data['data'].length > 0) {
        for (var i = 0; i < data['data'].length; i++) {
          var province = data['data'][i];
          var citys = province['children'];
          if (citys != null && citys.length > 0) {
            List<PickerItem> cityPickerItems = [];
            for (int j = 0; j < citys.length; j++) {
              var city = citys[j];
              var areas = city['children'];
              if (areas != null && areas.length > 0) {
                List<PickerItem> areaPickerItems = [];
                for (int k = 0; k < areas.length; k++) {
                  var area = areas[k];
                  areaPickerItems.add(PickerItem(area['label']));
                  acodes.add(area['value']);
                }
                PickerItem cityPickerItem =
                    PickerItem(city['label'], child: areaPickerItems);
                cityPickerItems.add(cityPickerItem);
              }
            }
            PickerItem provincePickerItem =
                PickerItem(province['label'], child: cityPickerItems);
            provincePickerItems.add(provincePickerItem);
          }
        }
        setState(() {
          provincePickerItems = provincePickerItems;
          acodes = acodes;
        });
      }
    });
  }

  void getUserInfoByPhone(String phone) {
    if (phone == "" || phone == null) {
      return;
    }
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) {
          return Center(
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4.0),
                  color: Colors.white),
              padding: EdgeInsets.all(20),
              child: Loading(
                color: Colors.blueAccent,
                text: "加载中...",
              ),
            ),
          );
        });
    DioUtil.postHttp("user/getUserByPhone/" + phone, params: {},
        onSuccess: (res) {
      Map<String, dynamic> data = jsonDecode(res);
      if (data['code'] == 0 && data['data'] != null) {
        _nameCtrl.text = data['data']['realName'];
        _cardIdCtrl.text = data['data']['idCard'];
        _addressCtrl.text = data['data']['address'];
        setState(() {
          userId = data['data']['id'];
        });
      }
      Navigator.pop(context, 0);
    });
  }

  List<PickerItem> insureItemList = [new PickerItem("不投保")];
  List<String> insureLabels = ['不投保'];
  List<String> insureKeys = ['no'];

  void getInsureList() {
    String userId = SpUtil.preferences.getString("userId");
    DioUtil.postHttp("insureDetail/getInsureByMngId/" + userId, params: {},
        onSuccess: (res) {
      Map<String, dynamic> data = jsonDecode(res);
      List<String> tempInsureLabels = [];
      List<String> tempInsureKeys = [];
      List<PickerItem> tempInsureItemList = [];
      if (data['data'] != null && data['data'].length > 0) {
        for (var i = 0; i < data['data'].length; i++) {
          var insure = data['data'][i];
          String code = insure['code'].toString();
          String name = insure['name'].toString();
          tempInsureItemList.add(new PickerItem(name));
          tempInsureKeys.add(code);
          tempInsureLabels.add(name);
        }
      }
      if (tempInsureLabels.length == 0) {
        tempInsureLabels = ['不投保'];
      }
      if (tempInsureLabels.length == 0) {
        tempInsureKeys = ['no'];
      }
      if (tempInsureItemList.length == 0) {
        tempInsureItemList = [PickerItem("不投保")];
      }
      setState(() {
        insureItemList = tempInsureItemList;
        insureKeys = tempInsureKeys;
        insureLabels = tempInsureLabels;
      });
      print('长度' + insureLabels.length.toString());
    });
  }

  bool isEmptyValue(String text) {
    return !(text != null && text != "");
  }

  Widget title(String title) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 20, horizontal: 16),
      child: Text(title, style: TextStyle(fontSize: 14, color: Colors.grey)),
    );
  }

  String getStringFromBytes(ByteData data) {
    final buffer = data.buffer;
    var list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    return utf8.decode(list);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(widget.title),
        ),
        body: Stack(children: <Widget>[
          SingleChildScrollView(
            padding: EdgeInsets.fromLTRB(0, 0, 0, 70),
            child: Form(
              key: _uplateFormKey,
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    title('填写车主信息'),
                    CellGroup(children: [
                      Field(
                        label: "手机号",
                        placeholder: "请输入车主手机号",
                        controller: _phoneCtrl,
                        onChange: (val) {},
                        require: true,
                        right: NButton(
                          text: "查询",
                          type: "primary",
                          size: "small",
                          onClick: () {
                            getUserInfoByPhone(_phoneCtrl.text);
                          },
                        ),
                      ),
                      Field(
                        label: '车主姓名',
                        require: true,
                        placeholder: "请输入车主姓名",
                        controller: _nameCtrl,
                        onChange: (val) {},
                      ),
                      Field(
                        label: '身份证号',
                        require: true,
                        placeholder: "请输入身份证号",
                        controller: _cardIdCtrl,
                        onChange: (val) {},
                      ),
                      Field(
                        label: '家庭地址',
                        placeholder: "请输入车主家庭地址",
                        controller: _addressCtrl,
                        onChange: (val) {},
                      ),
                    ]),
                    title('填写车辆信息'),
                    CellGroup(children: [
                      Cell(
                        title: "车辆类型",
                        require: true,
                        isLink: true,
                        value: electrTypeLabels[electrTypeIndex],
                        onClick: () {
                          showModalBottomSheet(
                              context: context,
                              builder: (BuildContext context) {
                                return Picker(
                                  colums: electrTypeItems,
                                  defaultIndex: electrTypeIndex,
                                  showToolbar: true,
                                  onConfirm: (values, index) {
                                    setState(() {
                                      electrTypeIndex = index;
                                    });
                                    Navigator.of(context).pop();
                                  },
                                  onCancel: (values, index) {
                                    Navigator.of(context).pop();
                                  },
                                );
                              });
                        },
                      ),
                      Field(
                        labelWidth: 105,
                        require: true,
                        label: "防盗芯片编号",
                        placeholder: "请输入防盗芯片编号",
                        controller: _rfidCtrl,
                        onChange: (val) {},
                      ),
                      Cell(
                        title: "所属区域",
                        isLink: true,
                        require: true,
                        value: areaNames,
                        onClick: () {
                          showModalBottomSheet(
                              context: context,
                              builder: (BuildContext context) {
                                return Picker(
                                  colums: provincePickerItems,
                                  defaultIndex: [0, 0, 0],
                                  showToolbar: true,
                                  level: 3,
                                  onConfirm: (values, index) {
                                    print(values);
                                    print(acodes[index[2]]);
                                    setState(() {
                                      areaNames = values.join("/");
                                      areaCode = acodes[index[2]].toString();
                                    });
                                    Navigator.of(context).pop();
                                  },
                                  onCancel: (values, index) {
                                    Navigator.of(context).pop();
                                  },
                                );
                              });
                        },
                      ),
                      Field(
                        require: true,
                        label: '车架号',
                        placeholder: "请输入车架号",
                        controller: _frameCodeCtrl,
                        onChange: (val) {},
                      ),
                      Field(
                        require: true,
                        label: '车牌号',
                        placeholder: "请输入车牌号",
                        controller: _plateCodeCtrl,
                        onChange: (val) {},
                      ),
                      Cell(
                          title: "购车日期",
                          require: true,
                          value: buyDate != null
                              ? formatDateWithYear(buyDate)
                              : '',
                          isLink: true,
                          onClick: () {
                            DatePicker.showDatePicker(context,
                                showTitleActions: true,
                                minTime: DateTime(2014, 1, 1),
                                maxTime: DateTime.now(), onConfirm: (date) {
                              setState(() {
                                buyDate = date;
                              });
                            },
                                currentTime: DateTime.now(),
                                locale: LocaleType.zh);
                          }),
                      Field(
                        label: '电机号',
                        placeholder: "请输入电机号",
                        controller: _engineCtrl,
                        onChange: (val) {},
                      ),
                      Cell(
                        title: "保险产品",
                        isLink: true,
                        value: insureLabels.length > 0
                            ? insureLabels[electrInsIndex]
                            : "不投保",
                        onClick: () {
                          showModalBottomSheet(
                              context: context,
                              builder: (BuildContext context) {
                                return Picker(
                                  colums: insureItemList,
                                  defaultIndex: electrInsIndex,
                                  showToolbar: true,
                                  onConfirm: (values, index) {
                                    setState(() {
                                      electrInsIndex = index;
                                    });
                                    Navigator.of(context).pop();
                                  },
                                  onCancel: (values, index) {
                                    Navigator.of(context).pop();
                                  },
                                );
                              });
                        },
                      ),
                      Field(
                        label: '车辆品牌',
                        placeholder: "请输入车辆品牌",
                        controller: _brandCtrl,
                        onChange: (val) {},
                      ),
                      Field(
                        label: '车辆颜色',
                        placeholder: "请输入车辆颜色",
                        controller: _colorCtrl,
                        onChange: (val) {},
                      ),
                    ]),
                    SizedBox(
                      height: 12,
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Column(children: <Widget>[
                            Container(
                              padding: EdgeInsets.all(10),
                              height: 120,
                              child: _imageUrl1 == null || _imageUrl1==""
                                  ? Container(
                                      height: 100,
                                      width: 100,
                                      child: Icon(
                                        Icons.image,
                                        color: Colors.black12,
                                        size: 80,
                                      ))
                                  : Image.network("http://electr-imgserver.oss-cn-hangzhou.aliyuncs.com/"+_imageUrl1),
                            ),
                            OutlineButton(
                              onPressed: () {
                                _showActionSheet(context, 1);
                              },
                              child: Text("上传车辆照片"),
                              borderSide: BorderSide(color: Colors.lightBlue),
                            )
                          ]),
                        ),
                        Expanded(
                            flex: 1,
                            child: Column(children: <Widget>[
                              Container(
                                height: 120,
                                padding: EdgeInsets.all(10),
                                child: _imageUrl2 == null || _imageUrl2==""
                                    ? Container(
                                        height: 100,
                                        width: 100,
                                        child: Icon(
                                          Icons.image,
                                          color: Colors.black12,
                                          size: 80,
                                        ))
                                    : Image.network("http://electr-imgserver.oss-cn-hangzhou.aliyuncs.com/"+_imageUrl2),
                              ),
                              OutlineButton(
                                onPressed: () {
                                  _showActionSheet(context, 2);
                                },
                                child: Text("上传身份证照片"),
                                borderSide: BorderSide(color: Colors.lightBlue),
                              )
                            ])),
                      ],
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Column(children: <Widget>[
                            Container(
                              height: 120,
                              padding: EdgeInsets.all(10),
                              child: _imageUrl3 == null || _imageUrl3==""
                                  ? Container(
                                      height: 100,
                                      width: 100,
                                      child: Icon(
                                        Icons.image,
                                        color: Colors.black12,
                                        size: 80,
                                      ))
                                  : Image.network("http://electr-imgserver.oss-cn-hangzhou.aliyuncs.com/"+_imageUrl3),
                            ),
                            OutlineButton(
                              onPressed: () {
                                _showActionSheet(context, 3);
                              },
                              child: Text("上传安装现场照片"),
                              borderSide: BorderSide(color: Colors.lightBlue),
                            )
                          ]),
                        ),
                        Expanded(
                            flex: 1,
                            child: Column(children: <Widget>[
                              Container(
                                height: 120,
                                padding: EdgeInsets.all(10),
                                child: _imageUrl4 == null || _imageUrl4==""
                                    ? Container(
                                        height: 100,
                                        width: 100,
                                        child: Icon(
                                          Icons.image,
                                          color: Colors.black12,
                                          size: 80,
                                        ))
                                    : Image.network("http://electr-imgserver.oss-cn-hangzhou.aliyuncs.com/"+_imageUrl4),
                              ),
                              OutlineButton(
                                onPressed: () {
                                  _showActionSheet(context, 4);
                                },
                                child: Text("上传登记表格照片"),
                                borderSide: BorderSide(color: Colors.lightBlue),
                              )
                            ])),
                      ],
                    )
                  ]),
            ),
          ),
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    child: NButton(
                        disabled: _uploading,
                        type: 'info',
                        height: 55,
                        onClick: () {
                          if (_uplateFormKey.currentState.validate()) {
                            _uplateFormKey.currentState.save();
                            saveElectrInfo();
                          }
                        },
                        text: '保存'),
                  ),
                ),
                Expanded(
                  child: Container(
                    color: Colors.green,
                    child: NButton(
                        type: 'primary',
                        height: 55,
                        onClick: () {
                          resetForm();
                        },
                        text: "清空"),
                  ),
                ),
              ],
            ),
          )
        ]));
  }
}
